package server.configuration;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 负责解析配置文件，并配置mapper
 *
 * @author leonzhangxf
 */
public class MapperParser {

    public static void parse(Server server, Mapper mapper) throws Exception {
        // 获取根目录
        String appBase = server.getAppBase();
        File webapps = new File(appBase);

        Map<String, MapperHost> hostMap = new HashMap<>();
        mapper.setHostMap(hostMap);

        MapperHost mapperHost = new MapperHost();
        mapperHost.setName(server.getHostname());
        hostMap.put(server.getHostname(), mapperHost);

        Map<String, MapperContext> contextMap = new HashMap<>();

        File[] files = webapps.listFiles();
        for (File file : Objects.requireNonNull(files)) {
            String name = file.getName();
            MapperContext mapperContext = new MapperContext();
            mapperContext.setName(name);

            File webConfigFile = Arrays.stream(Objects.requireNonNull(file.listFiles()))
                .filter(configFile -> "web.xml".equals(configFile.getName()))
                .findFirst().orElseThrow(() -> new RuntimeException("could not find web.xml"));
            Map<String, HttpServlet> servletMap = loadServlet(webConfigFile);
            mapperContext.setServletMap(servletMap);

            contextMap.put(name, mapperContext);
        }
        mapperHost.setContextMap(contextMap);
    }


    /**
     * 加载解析web.xml，初始化Servlet
     */
    private static Map<String, HttpServlet> loadServlet(File webConfigFile) throws FileNotFoundException, MalformedURLException {
        InputStream resourceAsStream = new FileInputStream(webConfigFile);
        SAXReader saxReader = new SAXReader();
        Map<String, HttpServlet> servletMap = new HashMap<>();

        URL url = new URL("file", null, -1, webConfigFile.getParent() + "/");
        URLClassLoader classLoader = new URLClassLoader(new URL[]{url}, MapperParser.class.getClassLoader());

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass, true, classLoader).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return servletMap;
    }
}
